package cn.workreport.config;

import cn.workreport.modules.users.entity.UserEntity;
import cn.workreport.util.UserChacheFromToken;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充处理类
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 在执行mybatisPlus的insert()时，为我们自动给某些字段填充值，这样的话，我们就不需要手动给insert()里的实体类赋值了
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        if (null != currentLoginUser) {
            // 其中方法参数中第一个是前面自动填充所对应的字段，第二个是要自动填充的值。第三个是指定实体类的对象
            this.setFieldValByName("creatorId", currentLoginUser.getId(), metaObject);
            this.setFieldValByName("creatorName", currentLoginUser.getUsername(), metaObject);
            this.setFieldValByName("createdTime", new Date(), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        if (null != currentLoginUser) {
            this.setFieldValByName("modifierId", currentLoginUser.getId(), metaObject);
            this.setFieldValByName("modifierName", currentLoginUser.getUsername(), metaObject);
            this.setFieldValByName("modifiedTime", new Date(), metaObject);
        }
    }
}
